from django.utils import timezone
from rest_framework import serializers

from apps.OrderManagement.models import UserPackage, Order
from apps.PackageManagement.models import Package
from apps.PaymentManagement.views import get_active_package
from apps.UserManagement.models import User


class UserPackageListSerializer(serializers.ModelSerializer):
    package_name = serializers.CharField(source='package.name')
    username = serializers.CharField(source='user.username')
    email = serializers.CharField(source='user.email')

    class Meta:
        model = UserPackage
        fields = ('id', 'username', 'email', 'status', 'package_name', 'expiration_time')


class UserPackageCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserPackage
        fields = ('id', 'user', 'package', 'cost', 'subscription_time', 'expiration_time', 'status')


class OrderCreateSerializer(serializers.ModelSerializer):
    user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all())
    package = serializers.PrimaryKeyRelatedField(queryset=Package.objects.all())

    class Meta:
        model = Order
        fields = '__all__'
        read_only_fields = (
            'order_no', 'create_time', 'update_time',
            'transaction_id', 'status', 'order_type', 'paid_time'
        )
        extra_kwargs = {
            'user': {'required': True},
            'package': {'required': True},
            'amount': {'required': False},
            'payment_method': {'required': False}
        }

    def validate(self, attrs):
        user = attrs['user']
        new_package = attrs['package']

        # 查找本套餐最新记录
        latest_self_pkg = UserPackage.objects.filter(
            user=user,
            package=new_package
        ).order_by('-expiration_time').first()

        # 判断续费条件：存在未过期记录
        if latest_self_pkg and latest_self_pkg.expiration_time > timezone.now():
            attrs['order_type'] = 'renewal'
        else:
            # 判断是否升级（比较套餐优先级）
            current_active = get_active_package(user)
            if current_active and new_package.get_priority() > current_active.package.get_priority():
                attrs['order_type'] = 'upgrade'
            else:
                attrs['order_type'] = 'new'

        return attrs


class OrderSerializer(serializers.ModelSerializer):
    user = serializers.SerializerMethodField(help_text="用户信息")
    package = serializers.SerializerMethodField(help_text="套餐信息")
    create_time = serializers.ReadOnlyField()
    order_no = serializers.ReadOnlyField()

    class Meta:
        model = Order
        fields = [
            'id',
            'order_no',
            'order_type',
            'user',
            'package',
            'amount',
            'status',
            'payment_method',
            'transaction_id',
            'create_time',
            'update_time'
        ]

    def get_user(self, obj):
        return {
            'id': obj.user.id,
            'username': obj.user.username,
            'email': obj.user.email
        }

    def get_package(self, obj):
        # 获取与该订单相关的用户套餐
        user_package = UserPackage.objects.filter(user=obj.user, package=obj.package).first()

        if user_package:
            return {
                'id': obj.package.id,
                'name': obj.package.name,
                'duration': obj.package.duration_to_days(),
                'price': obj.package.price,
                'subscription_time': user_package.subscription_time,
                'expiration_time': user_package.expiration_time
            }
        else:
            # 如果没有相关的用户套餐信息
            return {
                'id': obj.package.id,
                'name': obj.package.name,
                'duration': obj.package.duration_to_days(),
                'price': obj.package.price,
                'subscription_time': None,
                'expiration_time': None
            }
